package cn.shuangliang.contract.web.interceptor;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author oldliu
 * @since 1.0
 */
//字符集。。。
@Service("role")
public class RoleInterceptor extends HandlerInterceptorAdapter {
    @Override//handler被拦截的对象，一般是controller中的方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //>>>request.setCharacterEncoding("utf-8");
        if (request.getSession().getAttribute("USER_LOGIN") == null) {
            request.setAttribute("msg", "您还没有登录，不能访问此地址！");
            //直接return false,页面一片空白，必须给他一个视图
            request.getRequestDispatcher("/login.jsp").forward(request, response);

            return false;
        }
        return true;//return false，后面的不执行；return true,放行！
    }

    @Override//modelAndView是返回值。。。所有的controler，最终返回值都是ModelAndView 格式。。。
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("当前的请求地址是："+request.getServletPath()+"...处理器是" + handler + ",返回值是" + modelAndView);
        if (modelAndView != null)
            System.out.println("返回的数据是" + modelAndView.getModel() + ",视图地址：" + modelAndView.getViewName());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图渲染也结束了。。。"+handler+","+ex);
    }
}
